package com.kkwrite.regimen.consumer.common;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.Security;

/**
 * Created by lisha on 2018/7/17 19:14.
 * AES128 算法
 * <p>
 * CBC 模式
 * <p>
 * PKCS7Padding 填充模式
 * <p>
 * CBC模式需要添加一个参数iv--对称解密算法初始向量 iv
 * <p>
 * 介于java 不支持PKCS7Padding，只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别
 * 要实现在java端用PKCS7Padding填充，需要用到bouncycastle组件来实现
 *
 * @author lisha
 */
public class AESUtil {
    /**
     * 算法名称
     */
    private static final String KEY_ALGORITHM = "AES";
    /**
     * 加解密算法/模式/填充方式
     */
    private static final String ALGORITHM_STRING = "AES/CBC/PKCS7Padding";
    /**
     * 默认对称解密算法初始向量 iv
     */
    private static byte[] iv = {0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x30, 0x36, 0x30, 0x37, 0x30, 0x38};

    private static Key getKey(byte[] keyBytes) {
        // 如果密钥不足16位，那么就补足.  这个if中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }

    /**
     * 加密方法-使用默认iv
     *
     * @param content   待加密数据
     * @param keyString key字符串
     * @return string
     * @throws GeneralSecurityException 异常
     */
    public static String encrypt(String content, String keyString)
            throws GeneralSecurityException {
        return encrypt(content, keyString, Base64.encodeBase64String(iv));
    }

    /**
     * 加密方法
     *
     * @param content   待加密数据
     * @param keyString key字符串
     * @param ivs       自定义iv
     * @return string
     * @throws GeneralSecurityException 异常
     */
    public static String encrypt(String content, String keyString, String ivs)
            throws GeneralSecurityException {
        Key key = getKey(Base64.decodeBase64(keyString));
        Cipher cipher = Cipher.getInstance(ALGORITHM_STRING, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(Base64.decodeBase64(ivs)));
        return Base64.encodeBase64String(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 解密方法-使用默认iv
     *
     * @param encryptedData 待解密的数据
     * @param keyString     key字符串
     * @return string
     * @throws GeneralSecurityException 异常
     */
    public static String decrypt(String encryptedData, String keyString)
            throws GeneralSecurityException {
        return decrypt(encryptedData, keyString, Base64.encodeBase64String(iv));
    }

    /**
     * 解密方法
     *
     * @param encryptedData 待解密的数据
     * @param keyString     key字符串
     * @param ivs           自定义iv
     * @return string 解密得到的字符串
     * @throws GeneralSecurityException 异常
     */
    public static String decrypt(String encryptedData, String keyString, String ivs)
            throws GeneralSecurityException {
        Key key = getKey(Base64.decodeBase64(keyString));
        Cipher cipher = Cipher.getInstance(ALGORITHM_STRING, "BC");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(Base64.decodeBase64(ivs)));
        return new String(cipher.doFinal(Base64.decodeBase64(encryptedData)), StandardCharsets.UTF_8);
    }

}
